package edu.sdbi.judge.service.impl;

import com.alibaba.fastjson.JSONObject;
import edu.sdbi.judge.domain.vo.StudentResult;
import edu.sdbi.judge.mapper.NewsTypeMapper;
import edu.sdbi.judge.mapper.VisitMapper;
import edu.sdbi.judge.service.GetJudgeIpResultService;
import edu.sdbi.judge.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * 考核4. 	新闻详情
 *
 * @author 周涛
 */
@Order(4)
@Service
public class Judge_4 implements GetJudgeIpResultService {

    @Autowired
    private HttpUtil httpUtil;

    @Autowired
    private NewsTypeMapper newsTypeMapper;

    @Autowired
    private VisitMapper visitMapper;

    @Override
    public StudentResult getJudgeIpResult(String ip) {
        StudentResult studentResult = new StudentResult();
        studentResult.setItemNumber("4");

        double score = 0;
        try {
            // 测试有效新闻ID
            boolean validIdTestPassed = testValidNewsId(ip);
            if (validIdTestPassed) {
                score += 2;
            }
            // 测试访问日志记录
            boolean accessLogTestPassed = testAccessLogRecording(ip);
            if (accessLogTestPassed) {
                score += 2;
            }
        } catch (Exception e) {
            studentResult.setResult("接口调用异常：" + e.getMessage());
            e.printStackTrace();
        }
        studentResult.setScore(score);
        return studentResult;
    }

    // 测试有效新闻ID
    private boolean testValidNewsId(String ip) throws Exception {
        // 有效新闻ID (假设ID为1的新闻存在)
        String newsId = "2";
        String url = "http://" + ip + "/news/detail?id=" + newsId;

        String result = httpUtil.doGet(url, null, null);
        if (result == null) return false;

        JSONObject json = JSONObject.parseObject(result);

        // 检查状态码和消息
        if (json.getIntValue("code") != 200) {
            return false;
        }

        // 获取数据
        JSONObject data = json.getJSONObject("data");
        if (data == null) {
            return false;
        }

        // 验证返回的新闻ID是否正确
        String returnedId = data.getString("id");
        return newsId.equals(returnedId);
    }

    // 测试访问日志记录
    private boolean testAccessLogRecording(String ip) throws Exception {
        // 发送请求，验证访问量是否增加
        String newsId = "2";
        String url = "http://" + ip + "/news/detail?id=" + newsId;
        int count1 = visitMapper.countByNewsId(newsId);
        httpUtil.doGet(url, null, null);
        int count2 = visitMapper.countByNewsId(newsId);
        return count2 > count1;
    }

}